'use client';

import { use, useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { Copy, Trash2, AlertTriangle } from 'lucide-react';
import { fetchApi, getDateTime } from '@/lib/utils/client';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';
import NavTabs from '../../navTabs';
import type { InventoryListResponse, InventoryRow, UseCouponResponse } from '@/types/store';

const PER_PAGE = 30;
const MASK_PLACEHOLDER = '* * * * * * * * * * * * * * * *';

function formatExpiryDate(iso: string): string
{
	const d = new Date(iso);
	const y = d.getFullYear();
	const m = String(d.getMonth() + 1).padStart(2, '0');
	const day = String(d.getDate()).padStart(2, '0');
	return `${y}-${m}-${day}`;
}

export default function InventoryDetailPage({ params }: { params: Promise<{ productID: string }> })
{
	const { productID } = use(params);
	const productIdNum = parseInt(productID, 10);

	const [items, setItems] = useState<InventoryRow[]>([]);
	const [total, setTotal] = useState(0);
	const [page, setPage] = useState(1);
	const [loading, setLoading] = useState(true);
	const [revealedCodes, setRevealedCodes] = useState<Record<number, string>>({});
	const [justRevealedID, setJustRevealedID] = useState<number|null>(null);
	const [copiedID, setCopiedID] = useState<number|null>(null);

	const load = useCallback(async () => {
		setLoading(true);
		const res = await fetchApi<InventoryListResponse>(
			`/api/store/inventory?productID=${productIdNum}&page=${page}&perPage=${PER_PAGE}`,
			{ silent: true }
		);
		if (res.success && res.data) {
			setItems(res.data.list);
			setTotal(res.data.total);
		}
		else {
			setItems([]);
			setTotal(0);
		}
		setLoading(false);
	}, [productIdNum, page]);

	useEffect(() => {
		load();
	}, [load]);

	const handleUse = async (inv: InventoryRow) => {
		if (inv.isExpired) {
			return;
		}

		const ok = window.confirm('쿠폰을 확인하면 사용 처리되며 환불받을 수 없습니다.\n계속하시겠습니까?');

		if (!ok) {
			return;
		}

		const res = await fetchApi<UseCouponResponse>(`/api/store/inventory/${inv.id}/use`, {
			method: 'POST',
			silent: true
		});

		if (res.success && res.data) {
			setRevealedCodes(prev => ({ ...prev, [inv.id]: res.data!.code }));
			setJustRevealedID(inv.id);
			setItems(prev => prev.map(it =>
				it.id === inv.id
					? { ...it, usedAt: res.data!.usedAt, code: res.data!.code }
					: it
			));
			// 잠시 강조 후 해제
			window.setTimeout(() => {
				setJustRevealedID(curr => (curr === inv.id ? null : curr));
			}, 3000);
			return;
		}

		window.alert(res.message || '쿠폰 사용 처리에 실패했습니다.');
	};

	const handleDelete = async (inv: InventoryRow) => {
		const ok = window.confirm('보관함에서 삭제하시겠습니까?');

		if (!ok) {
			return;
		}

		const res = await fetchApi(`/api/store/inventory/${inv.id}`, {
			method: 'DELETE',
			silent: true
		});

		if (res.success) {
			setItems(prev => prev.filter(it => it.id !== inv.id));
			setTotal(prev => Math.max(0, prev - 1));
		}
		else {
			window.alert(res.message || '삭제에 실패했습니다.');
		}
	};

	const handleCopy = async (code: string, id: number) => {
		try {
			await navigator.clipboard.writeText(code);
			setCopiedID(id);
			window.setTimeout(() => {
				setCopiedID(curr => (curr === id ? null : curr));
			}, 1500);
		}
		catch {
			window.prompt('아래 코드를 복사해주세요:', code);
		}
	};

	const productName = items[0]?.productName ?? '';
	const productThumbnail = items[0]?.productThumbnail ?? null;
	const gameName = items[0]?.gameName ?? '';

	return (
		<>
			<NavTabs />

			<div className='max-w-3xl px-4 sm:px-6 pb-8'>
				<div className='mb-4'>
					<Link href='/inventory' className='text-sm text-blue-600 dark:text-blue-400 hover:underline'>
						＜ 보관함으로
					</Link>
				</div>

				{/* 빨간 경고 안내 — 사용 시 환불 불가 */}
				<div className='flex items-start gap-2 mb-4 px-3 py-2.5 border border-red-300 dark:border-red-900/60 bg-red-50 dark:bg-red-950/30 rounded'>
					<AlertTriangle className='size-4 text-red-600 dark:text-red-400 shrink-0 mt-0.5' />
					<p className='text-xs sm:text-sm text-red-700 dark:text-red-300 leading-relaxed'>
						쿠폰 코드를 확인하면 <strong>즉시 사용 처리</strong>되며 <strong>환불받을 수 없습니다.</strong> 신중하게 확인해주세요.
					</p>
				</div>

				{!loading && items.length > 0 && (
					<div className='flex items-center gap-3 mb-4'>
						{productThumbnail && (
							<div className='w-16 h-16 sm:w-20 sm:h-20 bg-neutral-100 dark:bg-neutral-800 rounded overflow-hidden flex-shrink-0'>
								{/* eslint-disable-next-line @next/next/no-img-element */}
								<img src={productThumbnail} alt={productName} className='w-full h-full object-contain' />
							</div>
						)}
						<div className='min-w-0'>
							<div className='text-xs text-purple-600 dark:text-purple-400 truncate'>{gameName}</div>
							<h1 className='text-lg sm:text-xl font-bold truncate' title={productName}>{productName}</h1>
							<div className='text-xs text-neutral-500'>총 {total.toLocaleString()}장</div>
						</div>
					</div>
				)}

				{loading ? (
					<Loading />
				) : items.length === 0 ? (
					<div className='text-center py-20 text-neutral-500'>보관함에 이 상품의 쿠폰이 없습니다.</div>
				) : (
					<>
						<ul className='border border-neutral-200 dark:border-neutral-800 rounded-lg bg-white dark:bg-neutral-900 divide-y divide-neutral-200 dark:divide-neutral-800'>
							{items.map((it) => {
								const reveal = revealedCodes[it.id] ?? it.code;
								const expired = it.isExpired;
								const justReveal = justRevealedID === it.id;
								const copied = copiedID === it.id;

								return (
									<li
										key={it.id}
										className='p-3 sm:p-4 flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4'
									>
										{/* 코드 영역 */}
										<div className='flex-1 min-w-0'>
											<div className='flex items-center gap-2 flex-wrap mb-1'>
												{reveal ? (
													<>
														<input
															type='text'
															readOnly
															value={reveal}
															onFocus={(e) => e.currentTarget.select()}
															className={`font-mono w-full sm:max-w-xs border rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900 select-all transition-shadow ${justReveal ? 'border-blue-500 ring-2 ring-blue-200 dark:ring-blue-900' : 'border-neutral-300 dark:border-neutral-700'}`}
															aria-label='쿠폰 코드'
														/>
														<button
															type='button'
															onClick={() => handleCopy(reveal, it.id)}
															className='inline-flex items-center justify-center p-2 rounded border border-neutral-300 dark:border-neutral-700 hover:bg-neutral-50 dark:hover:bg-neutral-800 text-neutral-600 dark:text-neutral-300 shrink-0'
															title='클립보드에 복사'
															aria-label='쿠폰 코드 복사'
														>
															<Copy className='size-4' />
														</button>
														{copied && (
															<span className='text-xs text-green-600 dark:text-green-400 whitespace-nowrap'>복사됨!</span>
														)}
														{justReveal && !copied && (
															<span className='text-xs text-blue-600 dark:text-blue-400 whitespace-nowrap'>방금 사용됨</span>
														)}
													</>
												) : expired ? (
													<>
														<input
															type='text'
															readOnly
															disabled
															value={MASK_PLACEHOLDER}
															className='font-mono w-full sm:max-w-xs border border-neutral-200 dark:border-neutral-800 rounded px-3 py-2 text-sm bg-neutral-100 dark:bg-neutral-800/40 text-neutral-400 cursor-not-allowed tracking-wider'
															aria-label='만료된 쿠폰 코드'
														/>
														<span className='text-xs text-red-600 dark:text-red-400 whitespace-nowrap'>만료</span>
													</>
												) : (
													<>
														<input
															type='text'
															readOnly
															value={MASK_PLACEHOLDER}
															onClick={() => handleUse(it)}
															className='font-mono w-full sm:max-w-xs border border-neutral-300 dark:border-neutral-700 rounded px-3 py-2 text-sm bg-neutral-50 dark:bg-neutral-800 text-neutral-400 tracking-wider cursor-pointer hover:border-blue-500 hover:text-neutral-500'
															aria-label='쿠폰 코드 (확인 버튼을 눌러주세요)'
														/>
														<button
															type='button'
															onClick={() => handleUse(it)}
															className='px-3 py-2 rounded text-sm font-semibold bg-blue-600 text-white hover:bg-blue-700 whitespace-nowrap shrink-0'
														>
															확인
														</button>
													</>
												)}
											</div>
											{it.expiresAt && !expired && (
												<p className='text-xs text-orange-600 dark:text-orange-400'>
													~ {formatExpiryDate(it.expiresAt)} 까지 사용 가능
												</p>
											)}
										</div>

										{/* 메타 정보 */}
										<div className='flex sm:flex-col gap-2 sm:gap-0 sm:items-end text-xs text-neutral-500 dark:text-neutral-400 whitespace-nowrap'>
											<span>
												<span className='sm:hidden'>구매: </span>
												<span className='hidden sm:inline'>구매 </span>
												{getDateTime(it.acquiredAt)}
											</span>
											<span>
												<span className='sm:hidden'>· 사용: </span>
												<span className='hidden sm:inline'>사용 </span>
												{it.usedAt ? getDateTime(it.usedAt) : '-'}
											</span>
										</div>

										{/* 삭제 */}
										<button
											type='button'
											onClick={() => handleDelete(it)}
											className='self-end sm:self-center inline-flex items-center justify-center p-1.5 rounded hover:bg-neutral-100 dark:hover:bg-neutral-800 text-neutral-500 hover:text-red-600 shrink-0'
											title='보관함에서 삭제'
											aria-label='삭제'
										>
											<Trash2 className='size-4' />
										</button>
									</li>
								);
							})}
						</ul>

						<div className='mt-4'>
							<Pagination total={total} page={page} perPage={PER_PAGE} onChange={setPage} />
						</div>
					</>
				)}
			</div>
		</>
	);
}